/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: mac
 * Date: 2022-09-11
 * Time: 20:35
 */
public class TestDemo1 {
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer("helloworld");
        System.out.println(sb.delete(5, 10).insert(0, "你好"));
    }
    private static StringBuffer func() {
        String str = "abcdef";
        return new StringBuffer(str);//调用构造方法
    }

    /**
     * String -> StringBuilder & StringBuffer
     * 使用构造方法
     * @param args
     */
    //最好这样使用：StringBuilder - 单线程 StringBuffer - 多线程
    public static void main4(String[] args) {
        StringBuilder stringBuilder = new StringBuilder("abcdef");
        stringBuilder.reverse();
        System.out.println(stringBuilder);

        //synchronized保证线程安全 - 锁
        StringBuffer stringBuffer1 = new StringBuffer();
        stringBuffer1.reverse();
    }
    //如果在循环里边进行字符串的拼接，尽量不要用String,用StringBuilder和StringBuffer即可
    public static void main3(String[] args) {
        /*String str = "abcdef";
        for (int i = 0; i < 10; i++) {
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append(str).append(i);
            str = stringBuilder.toString();
            //str += i;
        }
        System.out.println(str);*/

        String str = "abcdef";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(str);
        for (int i = 0; i < 10; i++) {
            stringBuilder.append(i);
        }
        str = stringBuilder.toString();
        System.out.println(str);
    }
    public static void main1(String[] args) {
        //String str = "abcdef";
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("abcdef");
        //str += "123";
        stringBuilder.append("123");
        //str = stringBuilder.toString();
        System.out.println(stringBuilder);
        //对比代码，底层的String会被优化为StringBuilder
    }
}
